import { ref, reactive } from 'vue'
import { updatePassWord } from '@/api/manager'
import { showModal, toast } from '@/composables/util'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
//修改密码
export const useRePassWord = () => {
  const formDrawerModel = ref(null)
  const ruleFormRef = ref(null)

  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: '',
  })

  const rules = reactive({
    oldpassword: {
      required: true,
    },
    password: {
      required: true,
    },
    repassword: {
      required: true,
    },
  })

  const showDrawerModel = (bol) => {
    formDrawerModel.value.showDrawer(bol)
  }

  const onSubmit = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        formDrawerModel.value.showLoading(true)
        updatePassWord(form)
          .then((res) => {
            toast('out success!')
            showDrawerModel(false)
          })
          .finally(() => formDrawerModel.value.showLoading(false))
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  return {
    form,
    rules,
    ruleFormRef,
    formDrawerModel,
    onSubmit,
    showDrawerModel,
  }
}

//退出登录
export const useLogOut = () => {
  const store = useStore()
  const router = useRouter()
  const outBtn = () => {
    showModal('is out ?').then(() => {
      store.dispatch('logout').finally((res) => {
        router.push('/login')
        toast('out success!')
      })
    })
  }

  return {
    outBtn,
  }
}

// 登录
export const useLogin = () => {
  const router = useRouter()
  const store = useStore()
  const form = reactive({
    username: '',
    password: '',
  })
  const loading = ref(false)
  const ruleFormRef = ref(null)
  const rules = reactive({
    username: {
      required: true,
    },
    password: {
      required: true,
    },
  })
  const onSubmit = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true
        store
          .dispatch('login', form)
          .then((res) => {
            toast('success login !')
            router.push('/')
          })
          .finally(() => (loading.value = false))
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  return {
    form,
    loading,
    ruleFormRef,
    rules,
    onSubmit,
  }
}
